package com.yhy.auth.extension.wechat;

import com.yhy.common.security.service.MyUserDetailsService;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 微信认证提供者
 *
 * @author <a href="mailto:xianrui0365@163.com">haoxr</a>
 */
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private MyUserDetailsService userDetailsService;

    public WechatAuthenticationProvider(MyUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public WechatAuthenticationProvider() {
    }

    /**
     * 微信认证
     *
     * @param authentication authentication
     * @return Authentication
     * @throws AuthenticationException AuthenticationException
     */
    @SneakyThrows
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WechatAuthenticationToken authenticationToken = (WechatAuthenticationToken) authentication;
//        String code = (String) authenticationToken.getPrincipal();
//        String encryptedData = authenticationToken.getEncryptedData();
//        String iv = authenticationToken.getIv();
//        this.obtainWechatParam();
//        UserDetails userDetails = userDetailsService.loadUserByUnionId(null, null, null);

        UserDetails userDetails = userDetailsService.loadUserByUsername("andy");
        WechatAuthenticationToken result = new WechatAuthenticationToken(userDetails, userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
